package com.ithuameng.cosy.mq.signal;

import com.ithuameng.cosy.constants.Constants;
import com.ithuameng.cosy.model.Message;
import com.ithuameng.cosy.model.Session;
import com.ithuameng.cosy.service.IMessageLogService;
import com.ithuameng.cosy.util.JSONUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
public class SignalRabbitTemplate {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private IMessageLogService messageLogService;

    /**
     * 消息发送到 集群中的每个实例，获取对应长连接进行消息写入
     *
     * @param message
     */
    public void push(Message message) {

        String msgId = UUID.randomUUID().toString().replace("-", "");

        messageLogService.saveMessageLog(msgId, Constants.PUSH_MESSAGE_ROUTING_KEY, JSONUtils.toJSONString(message));

        rabbitTemplate.convertAndSend(Constants.CIM_MESSAGE_DIRECT_EXCHANGE, Constants.PUSH_MESSAGE_ROUTING_KEY,
                JSONUtils.toJSONString(message), new CorrelationData(msgId));
    }

    /**
     * 消息发送到 集群中的每个实例，解决多终端在线冲突问题
     *
     * @param session
     */
    public void bind(Session session) {

        String msgId = UUID.randomUUID().toString().replace("-", "");

        messageLogService.saveMessageLog(msgId, Constants.BIND_MESSAGE_ROUTING_KEY, JSONUtils.toJSONString(session));

        rabbitTemplate.convertAndSend(Constants.CIM_MESSAGE_DIRECT_EXCHANGE, Constants.BIND_MESSAGE_ROUTING_KEY,
                JSONUtils.toJSONString(session), new CorrelationData(msgId));
    }
}
